<template>
  <div class="">
    <!-- 搜索框 -->
    <van-search
      @keydown.enter="inputChange"
      v-model="search"
      placeholder="请输入搜索关键词"
    />

    <!-- 历史记录 -->
    <div
      class="history"
      v-if="historyData.length && !list.length && !emptyStatus"
    >
      <div class="title">
        <p>历史记录</p>
        <p style="color:red;" @click="$store.commit('clear')">CLEAR</p>
      </div>
      <ul>
        <li
          @click="changeSearchHandel(item.name)"
          v-for="(item, index) in historyData"
          :key="index"
        >
          <p>{{ item.name }}</p>
          <span @click.stop="$store.commit('remove', index)"> X</span>
        </li>
      </ul>
    </div>
    <!-- 内容  -->
    <div class="content" v-else>
      <van-card
        v-for="(item, index) in list"
        :key="index"
        :price="item.price"
        :desc="item.desc"
        :title="item.name"
        :thumb="item.url"
        @click="toDetail(item)"
      />
    </div>
    <!-- 暂无数据展示 -->
    <van-empty v-if="emptyStatus" description="暂无数据" />
  </div>
</template>

<script>
import axios from "axios";
import { mapState } from "vuex";
export default {
  data() {
    return {
      search: "",
      list: [],
      backupsData: [],
      emptyStatus: false,
    };
  },
  mounted() {
    axios.get("data.json").then((res) => {
      this.backupsData = res.data;
    });
  },
  computed: {
    ...mapState(["historyData"]),
  },
  methods: {
    changeSearchHandel(val) {
      this.search = val;
      this.inputChange();
    },
    inputChange() {
      this.list = this.backupsData.filter((item) =>
        item.name.includes(this.search)
      );
      if (!this.list.length) {
        this.emptyStatus = true;
      } else {
        this.emptyStatus = false;
      }
    },
    toDetail(val) {
      this.$store.commit("addHistory", val);
      this.$router.push({ path: "/detail", query: { id: val.name } });
    },
  },
  components: {},
};
</script>

<style lang="scss">
.history {
  width: 100%;
  height: 300px;
  ul {
    width: 100%;
    display: flex;
    flex-wrap: wrap;
    li {
      display: table;
      padding: 3px 10px;
      border: 1px solid rgb(55, 210, 221);
      box-sizing: border-box;
      align-items: center;
      display: flex;
      margin: 10px;
      p {
        margin-right: 10px;
      }
    }
  }
}
.title {
  width: 100%;
  height: 30px;
  background-color: #fff;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 10px;
}
</style>
